//10进制转16进制补0
function dec2hex(dec, len) {
  var hex = "";
  while( dec ) {
  var last = dec & 15;
  hex = String.fromCharCode(((last>9)?55:48)+last) + hex;
  dec >>= 4;
  }
  if(len) {
  while(hex.length < len) hex = '0' + hex;
  }
  return hex;
}

// 高低位转换
function endianConv(num) {
  return num.toString('hex').match(/.{2}/g).reverse().join("")
}

// 十六进制转浮点数
function hexToFloat(hex) {
  // 将十六进制字符串转换为无符号整型数
  const intValue = parseInt(hex, 16);
  
  // 检查是否为负数
  const sign = intValue & 0x80000000 ? -1 : 1;
  
  // 指数提取
  const exponent = (intValue >> 23 & 0xFF) - 127;
  
  // 尾数提取
  const fraction = (intValue & 0x7FFFFF) / 0x800000;
  
  // 计算浮点数
  return sign * Math.pow(2, exponent) * (1 + fraction);
}

// 秒转时分秒
function convertSecondsToHMS(seconds) {
  var hours = Math.floor(seconds / 3600);
  var minutes = Math.floor((seconds % 3600) / 60);
  var remainingSeconds = seconds % 60;
 
  return hours.toString().padStart(2, '0') + ":" + minutes.toString().padStart(2, '0') + ":" + remainingSeconds.toString().padStart(2, '0');
}

// 字符串转十六进制
// position 默认0在后，传true则在前
function stringToHex(t, len, position) {
  for (var a = t.length, e = '', n = 0; n < a; n++) {
    var s = t.charCodeAt(n).toString(16)
    e = ''.concat(e).concat(1 == s.length ? '0'.concat(s) : s)
  }
  if(len) {
    if (position) {
      while(e.length < len) e = e + '0';
    } else {
      while(e.length < len) e = '0' + e;
    }
  }
  return e.toLocaleUpperCase()
}



function n(t) {
  for (var a, e, n = [], s = 0; s < t.length; s++) {
    ;
    (a = t.charCodeAt(s)), (e = [])
    do {
      e.push(255 & a), (a >>= 8)
    } while (a)
    n = n.concat(e.reverse())
  }
  return n
}

// sign
function checkEnd(str) {
  let itotal = 0,
    len = str.length,
    num = 0;
  while (num < len) {
    let s = str.substring(num, num + 2);
    itotal += parseInt(s, 16);
    num = num + 2;
  }
  let mode = itotal % 256;
  let shex = mode.toString(16);
  let iLen = shex.length;
  if (iLen < 2) {
    shex = "0" + shex;
  }
  return shex.toLocaleUpperCase();
}

function hexStringToByteArray(hexString) {
  var byteArray = new Uint8Array(hexString.match(/.{2}/g).map(function(hexVal) {
      return parseInt(hexVal, 16);
  }));
  return byteArray;
}


const crc32Table = (function() {
	var table = new Uint32Array(256);
	var n, c, k;

	for (n = 0; n < 256; n++) {
		c = n;
		for (k = 0; k < 8; k++)
			c = ((c >>> 1) ^ (c & 1 ? 0xedb88320 : 0)) >>> 0;
		table[n] = c;
	}
	return table;
})();

function crc32(data) {
  
	var length = data.length;
	var offset = 0;
	var crc = 0xffffffff;

	while (length-- > 0)
		crc = crc32Table[(crc ^ data.charCodeAt(offset++)) & 0xff] ^ (crc >>> 8);

	return (crc ^ 0xffffffff) >>> 0;
}



// length byte 长度 
function padHex(hex, length) {
  while (hex.length < length * 2) {
    hex = "0" + hex;
  }
  return hex;
}
 
/**
 * @name: 十六进制转换为ASCII
 * @msg: 
 * @param {*} hexCharCodeStr
 * @return {*}
 */
function hexCharCodeToStr(hexCharCodeStr) {
  var trimedStr = hexCharCodeStr.trim();
  var rawStr =
    trimedStr.substr(0, 2).toLowerCase() === "0x"
      ? trimedStr.substr(2)
      : trimedStr;
  var len = rawStr.length;
  if (len % 2 !== 0) {
    return "";
  }
  var curCharCode;
  var resultStr = [];
  for (var i = 0; i < len; i = i + 2) {
    curCharCode = parseInt(rawStr.substr(i, 2), 16);
    resultStr.push(String.fromCharCode(curCharCode));
  }
  return resultStr.join("");
}

// 匹配字符串中所有数字
// 返回数组
function extractNumbers(str) {
  return str.match(/\d+/g) || [];
}


 function dateFormat(fmt, date) {
        let o = {
            'M+': date.getMonth() + 1, //月份
            'd+': date.getDate(), //日
            'h+': date.getHours(), //小时
            'm+': date.getMinutes(), //分
            's+': date.getSeconds(), //秒
            'q+': Math.floor((date.getMonth() + 3) / 3), //季度
            S: date.getMilliseconds(), //毫秒
        }
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(
                RegExp.$1,
                (date.getFullYear() + '').substr(4 - RegExp.$1.length)
            )
        for (var k in o)
            if (new RegExp('(' + k + ')').test(fmt)) {
                // console.log(RegExp.$1.length)
                // console.log(o[k])
                fmt = fmt.replace(
                    RegExp.$1,
                    RegExp.$1.length == 1
                        ? (o[k] + '').padStart(3, '0')
                        : ('00' + o[k]).substr(('' + o[k]).length)
                )
            }
        return fmt
    }
    const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('')}${[hour, minute, second].map(formatNumber).join('')}`
}
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

// 将文字绘制到行 长文本自动换行 并返回行数
/**
 * params
 * @text           需要绘制的文本字符
 * @startX         第一行文本的起始X坐标
 * @startY         第一行文本的起始Y坐标
 * @lineHeight     文本行高
 * @MAX_WIDTH      单行文字最大宽度，超过临界值自动换行
 * return rowLength  返回绘制文本的行数
**/
function splitTextByWidth(text, MAX_WIDTH) {
  const ctx = wx.createCanvasContext('canvas');
  let allAtr = text.split('');
  let rowArr = []; // 拆分出来的每一行
  let rowStrArr = []; // 每一行的文字数组
  for (let i = 0; i < allAtr.length; i++) {
    const currentStr = allAtr[i];
    rowStrArr.push(currentStr);
    const rowStr = rowStrArr.join('');
    if (ctx.measureText(rowStr).width > MAX_WIDTH) {
      rowStrArr.pop(); // 删除最后一个
      rowArr.push(rowStrArr.join('')); // 完成一行
      rowStrArr = [currentStr];
      continue;
    }
    // 最后一个字母 直接添加到一行
    if (i === allAtr.length - 1) {
      rowArr.push(rowStr); // 完成一行
    }
  }

  // for (let i = 0; i < rowArr.length; i++) {
  //   ctx.fillText(rowArr[i], startX, startY + i * lineHeight);
  // }
  return rowArr;
}

// function splitTextByWidth(text, maxWidth, charWidth) {
//   let result = [];
//   let start = 0;
//   let lineWidth = 0;
//   while (start < text.length) {
//     let end = start + 1;
//     while (end <= text.length) {
//       let char = text.charAt(end - 1);
//       let charWidthPx = charWidth * (char === ' ' ? 2: 1); // 空格需要加上额外宽度
//       if (lineWidth + charWidthPx > maxWidth) {
//         result.push(text.slice(start, end - 1)); // 将上一个子字符串保存到结果中
//         start = end - 1; // 更新起始位置
//         lineWidth = 0;
//         break;
//       }
//       lineWidth += charWidthPx;
//       end++;
//     }
//     if (end > text.length) {
//       result.push(text.slice(start)); // 将最后一个子字符串保存到结果中
//       break;
//     }
//   }
//   return result;
// }
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
module.exports = {
  dec2hex,
  stringToHex,
  endianConv,
  hexToFloat,
  convertSecondsToHMS,
  checkEnd,
  hexStringToByteArray,
  hexCharCodeToStr,
  crc32,
  padHex,
  extractNumbers,
  dateFormat,
  formatTime,
  splitTextByWidth,
  sleep
}


